//
//  APPHud.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import SVProgressHUD
import RxSwift
import RxCocoa

let defaultDelay: Double = 1.5
typealias didHideClosure = () -> Void

class APPHud {
    static let shared = APPHud()
    
    init() {
        SVProgressHUD.setDefaultStyle(.dark)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showLoading(text: String? = nil, delay: Double = 0, closure: @escaping didHideClosure = {}) {
        SVProgressHUD.show(withStatus: text)
        if delay > 0 {
            SVProgressHUD.dismiss(withDelay: delay) {
                closure()
            }
        }
    }
    
    func showError(status: String,
                   delay: Double = defaultDelay,
                   closure: @escaping didHideClosure = {}) {
        APPErrorHUD.shared.show(status: status, dismissDelay: delay) {
            closure()
        }
    }
    
    func showSuccess(status: String,
                     delay: Double = defaultDelay,
                     closure: @escaping didHideClosure = {}) {
        APPErrorHUD.shared.show(status: status, dismissDelay: delay) {
            closure()
        }
    }
    
    func dismiss() {
        SVProgressHUD.dismiss()
    }
    
}

extension Reactive where Base == APPHud {
    
    func loading(text: String? = nil) -> Binder<Bool> {
        return Binder(base) { hud , loading in
            if loading {
                hud.showLoading(text: text)
            } else {
                hud.dismiss()
            }
        }
    }
    
}
